<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * App\Models\Auth
 *
 * @property int $id
 * @property string $name
 * @property int $pid
 * @property string $url
 * @method static \Illuminate\Database\Eloquent\Builder|Auth newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|Auth newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|Auth query()
 * @method static \Illuminate\Database\Eloquent\Builder|Auth whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Auth whereName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Auth wherePid($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Auth whereUrl($value)
 * @mixin \Eloquent
 */
class Expenses extends Model
{
    protected $table = 'expenses';

    public static $types = [
        'sport' => '娱乐',
        'shopping' => '购物',
        'education' => '教育',
        'health' => '健康',
        'home' => '居家',
        'restaurant' => '餐饮',
        'traffic' => '交通',
        'travel' => '旅行',
    ];

    /**
     * 根据年月获取支出总额
     * @param int $year 年
     * @param int $month 月
     * @param int $user_id 用户编号
     * @return float 支出总额
     */
    public static function getSumExpensesByYearMonth(int $year, int $month, int $user_id): float
    {
        $expenses = self::where('year', $year)
            ->where('month', $month)
            ->where('user_id', $user_id)
            ->where('soft_del', 1)
            ->sum('money');
        if (empty($expenses)) {
            $expenses = 0.00;
        }
        return number_format($expenses, 2, '.', '');
    }

    /**
     * 获取年消费总额
     * @param int $year
     * @param int $user_id
     * @return string
     */
    public static function getSumExpensesByYear(int $year, int $user_id): string
    {
        $expenses = self::where('year', $year)
            ->where('user_id', $user_id)
            ->where('soft_del', 1)
            ->sum('money');
        if (empty($expenses)) {
            $expenses = 0.00;
        }
        return number_format($expenses, 2, '.', '');
    }

    /**
     * 获取某年每个月的消费总额
     * @param int $year
     * @param int $user_id
     * @return array
     */
    public static function getMonthGroupExpensesByYear(int $year, int $user_id)
    {
        $list = self::where('year', $year)
            ->where('user_id', $user_id)
            ->where('soft_del', 1)
            ->select(['month', DB::raw('SUM(money) as amount')])
            ->groupBy('month')
            ->get()->toArray();
        return $list;
    }


    /**
     * 根据日期组织消费数据
     * @param array $list 至少包含字段 month year day money
     * @return array ['xxxx-xx-xx'=> [ array ]]
     */
    public static function dealExpensesListGroupByDay(array $list)
    {
        $new_list = [];
        foreach ($list as $l) {
            //组织一下年月日数据
            $date = $l['year'] . '-' . $l['month'] . '-' . $l['day'];
            $l['date'] = $date;
            // 金额格式化一下
            $l['money'] = format_money($l['money']);
            if (!isset($new_list[$date])) {
                $new_list[$date] = [];
            }
            $new_list[$date][] = $date;
        }
        return $new_list;
    }

    /**
     * 根据年月获取最后的消费记录
     * @param int $year 年
     * @param int $month 月
     * @param int $user_id 用户编号
     * @param int $limit 最后的消费记录(几条)
     * @return array 消费记录数据
     */
    public static function getLastExpensesByYearMonth(int $year, int $month, int $user_id, int $limit = 3): array
    {
        $list = self::where('year', $year)
            ->where('month', $month)
            ->where('soft_del', 1)
            ->where('user_id', $user_id)
            ->limit($limit)
            ->select(['year', 'month', 'day', 'type', 'money', 'title', 'content', 'create_time'])
            ->orderBy('year', 'desc')
            ->orderBy('month', 'desc')
            ->orderBy('day', 'desc')
            ->get()
            ->toArray();

        return empty($list) ? [] : $list;
    }


    /**
     * 根据年月获取消费记录 正序
     * @param int $year 年
     * @param int $month 月
     * @param int $user_id 用户编号
     * @return array 消费记录数据
     */
    public static function getExpensesByYearMonth(int $year, int $month, int $user_id): array
    {
        $list = self::where('year', $year)
            ->where('month', $month)
            ->where('soft_del', 1)
            ->where('user_id', $user_id)
            ->select(['year', 'month', 'day', 'type', 'money', 'title', 'content', 'create_time'])
            ->orderBy('year')
            ->orderBy('month')
            ->orderBy('day')
            ->get()
            ->toArray();

        return empty($list) ? [] : $list;
    }

    /**
     * 新增支出方法
     * @param float $money
     * @param int $year
     * @param int $month
     * @param int $day
     * @param string $type
     * @param int $user_id
     * @return bool
     */
    public static function addExpenses(float $money, int $year, int $month, int $day, string $type, int $user_id, string $title, string $content): bool
    {
        $timestamp = now();
        $data = [
            'user_id' => $user_id,
            'money' => $money,
            'year' => $year,
            'month' => $month,
            'day' => $day,
            'type' => $type,
            'title' => $title,
            'content' => $content,
            'create_time' => $timestamp,
            'update_time' => $timestamp
        ];
        return self::insert($data);
    }

    /**
     * 删除
     * @param int $id
     * @param int $user_id
     * @return bool|int
     */
    public static function deleteExpenses(int $id, int $user_id)
    {
        return self::where('id', $id)->where('user_id', $user_id)->update(['soft_del' => 0, 'update_time' => now()]);
    }

    /**
     * 获取用户有支出的年份 数据默认限制为最近十个年份
     * @param int $user_id
     * @param int $limit
     * @return array
     */
    public static function getHaveExpenseYear(int $user_id, int $limit = 10)
    {
        return self::where('user_id', $user_id)
            ->orderBy('year', 'desc')
            ->groupBy('year')
            ->limit($limit)
            ->pluck('year')->toArray();
    }

    /**
     * 获取有支出的年月数据
     * @param int $start_year 起始年份
     * @param int $end_year 结束年份
     * @param int $user_id 用户编号
     * @return array 年月数组
     */
    public static function getHaveExpenseMonth(int $start_year, int $end_year, int $user_id)
    {
        $list = self::where('year', '>=', $start_year)
            ->where('year', '<=', $end_year)
            ->where('user_id', $user_id)
            ->groupBy('year')
            ->groupBy('month')
            ->select(['year', 'month'])
            ->get()->toArray();
        // 处理一下数据
        $res = [];
        foreach ($list as $l) {
            $res[] = [
                'show' => $l['year'] . '年' . $l['month'] . '月',
                'year' => $l['year'],
                'month' => $l['month']
            ];
        }
        return $res;
    }


    /**
     * 传入一个支出金额 根据年月计算平均每日开销
     * @param int $year
     * @param int $month
     * @param float $expenses
     * @return string
     */
    public static function calculateMonthAvgExpenses(int $year, int $month, float $expenses)
    {
        // 处理一下分母为0的时候的问题
        if ($expenses == 0) {
            return 0;
        }
        //判断是否为当前月
        //当前月的话则需要除以已经经过的天数
        $now_year = (int)date('Y');
        $now_month = (int)date('m');
        if ($now_year === $year && $now_month === $month) {
            $day = (int)date('d');
        } else {
            $day = cal_days_in_month(CAL_GREGORIAN, $month, $year);
        }
        return number_format((($expenses * 100) / $day / 100), 2, '.', '');
    }


    /**
     * 获取某月支出分类所占比例和金额
     * @param int $year
     * @param int $month
     * @param int $user_id
     * @param float $expenses
     * @return array
     */
    public static function getMonthExpensesTypeRate(int $year, int $month, int $user_id, float $expenses): array
    {
        $list = self::where('year', $year)
            ->where('month', $month)
            ->where('soft_del', 1)
            ->where('user_id', $user_id)
            ->select(['type', DB::raw('SUM(money) as amount')])
            ->groupBy('type')
            ->get()->toArray();
        // 算一下比例
        foreach ($list as $key => $l) {
            $l['rate'] = ($l['amount'] * 100) / ($expenses * 100);
            $list[$key] = $l;
        }
        return $list;
    }

}
